package com.weme.home.fragment

import android.content.Intent
import android.graphics.Rect
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jeremyliao.liveeventbus.LiveEventBus
import com.purepulse.home.R
import com.purepulse.home.databinding.FragmentHomeHotBinding
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.weme.common.arouter.ARouterHelper
import com.weme.common.base.BaseFragment
import com.weme.common.network.OnLineErrorBean
import com.weme.common.util.*
import com.weme.common.view.MyStyledPlayerView
import com.weme.home.adapter.NewHomeAdapter
import com.weme.home.viewmode.HomeNewViewMode
import com.weme.home.viewmode.HomeViewMode
import dev.kratos.api.user_server.v1.GetOnlineListReply
import dev.kratos.api.user_server.v1.Users
import java.lang.ref.WeakReference

class HomeNewFragment : BaseFragment<FragmentHomeHotBinding, HomeNewViewMode>() {
    private var pageIndex: Int = 1
    private val mViewModel: HomeViewMode by activityViewModels()
    //  private var requestOptions = RequestOptions()
    private var showActivity = true
    private var oldPosition = 0

    private var visibleCount = 0
    private var usersList = mutableListOf<Users>()
    var palyVideoVidw: MyStyledPlayerView? = null

    private var player: ExoPlayer? = null

    private lateinit var homeHotAdapter: NewHomeAdapter
    override fun startOperate() {
        homeHotAdapter = NewHomeAdapter {
            viewModel.callsPhone(it)
        }
        player = ExoPlayer.Builder(requireContext()).build()
        player?.addListener(object : Player.Listener {
            override fun onPlaybackStateChanged(playbackState: Int) {
                super.onPlaybackStateChanged(playbackState)
                when (playbackState) {
                    Player.STATE_IDLE -> { // 播放器处于空闲状态
                    }
                    Player.STATE_BUFFERING -> { // 播放器正在缓冲
                    }
                    Player.STATE_READY -> { // 播放器已准备好播放
                        palyVideoVidw?.startVideo()
                    }
                    Player.STATE_ENDED -> { // 播放已结束
                    }
                }
            }

        })
        initRecyclerView()
        initRefreshLayout()

        pageIndex = 1
        viewModel.getOnlineList(pageIndex)


     LiveEventBus.get<Any>(LiveConfig.NET_WORK_HOME_NEW).observe(this) {
            if (it is GetOnlineListReply) {
                if (pageIndex == 1) {
                    usersList.clear()
                    usersList.addAll(it.usersList)
                    homeHotAdapter.submitList(usersList)
                    homeHotAdapter.notifyDataSetChanged()
                    mBinding.inEmpty.root.setVisible(it.usersCount == 0)
                } else {
                    usersList.addAll(it.usersList)
                    homeHotAdapter.addAll(it.usersList)
                }
                mBinding.refreshHome.finishRefresh()
                mBinding.refreshHome.finishLoadMore()
            } else if (it is OnLineErrorBean) {
                if (pageIndex == 1) {
                    mBinding.inEmpty.root.visible()
                    usersList.clear()
                    homeHotAdapter.notifyDataSetChanged()
                }


                mBinding.refreshHome.finishRefresh()
                mBinding.refreshHome.finishLoadMore()
            }
        }

    }

    private val autoPlayDelay = 500L
    private var isScrolling = false

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.e("tag","222")
        try {
            if(!TextUtils.isEmpty(data?.getStringExtra("9998"))){
                mBinding.refreshHome.autoRefresh()
            }
        }catch (e:Exception){

        }

    }
    class HomeHotHandle(homeHotFragment: HomeNewFragment) : Handler(Looper.getMainLooper()) {

        private val weakReference: WeakReference<HomeNewFragment> = WeakReference(homeHotFragment)

        override fun handleMessage(msg: Message) {
            val host = weakReference.get()
            if (host != null) {
                when (msg.what) {
                    host.AUTO_VIDEO -> {
                        Log.e("tag", "handleMessage")
                        host.isScrolling = false
                        if (host.showActivity) {
                            host.context?.run {
                                host.watchVideo((msg.obj as MyStyledPlayerView))

                            }
                        }
                    }

                }
            }
        }
    }

    var secondHandler: HomeHotHandle? = null
    val AUTO_VIDEO = 999

    private fun initRecyclerView() {
        secondHandler = HomeHotHandle(this)
        mBinding.rcvHomeList.apply { //            val gridLayoutManager = GridLayoutManager(requireContext(), 2)
            //            gridLayoutManager.recycleChildrenOnDetach = false
            //            layoutManager = gridLayoutManager
           // itemAnimator = null
            setHasFixedSize(true) //优化布局 固定宽高的作用
            setHasTransientState(true)
            // itemAnimator = null
            setItemViewCacheSize(20) // 设置可回收的 item 视图数量为 20
            adapter = homeHotAdapter



            mBinding.inEmpty.btRefresh.text = getString(com.example.resources.R.string.home_empty_btn)
          //  mBinding.inEmpty.btRefresh.setBackgroundResource(com.example.resources.R.mipmap.icon_empty_home_btn)
            mBinding.inEmpty.tvEmpty.text = getString(com.example.resources.R.string.home_empty_msg)
            mBinding.inEmpty.btRefresh.setOnClickListener {
                mBinding.refreshHome.autoRefresh()
            }
            homeHotAdapter.stateView = view //
            homeHotAdapter.submitList(usersList)
            addOnChildAttachStateChangeListener(object : RecyclerView.OnChildAttachStateChangeListener {
                override fun onChildViewAttachedToWindow(view: View) {
                    Log.e("tag", "rcvHomeList 恢复")
                }

                override fun onChildViewDetachedFromWindow(view: View) {
                    Log.e("tag", "rcvHomeList 回收") //   stopVideo()
                }

            })
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        if (!isScrolling) {
                            isScrolling = true
                            autoPlayVideo(recyclerView)


                            //                            handler.sendEmptyMessage(0)
                            //                            handler.postDelayed({
                            //                                isScrolling = false
                            //                                if (showActivity) {
                            //                                    context?.run {
                            //                                        autoPlayVideo(recyclerView)
                            //                                    }
                            //                                }
                            //                            }, autoPlayDelay.toLong())
                        }
                    } else { // 非 SCROLL_STATE_IDLE，重新计时
                        isScrolling = false
                        secondHandler?.removeMessages(AUTO_VIDEO) //handler.removeCallbacksAndMessages(null)
                        stopVideo()
                    }
                }

                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    val layoutManager = recyclerView.layoutManager
                    if (layoutManager is LinearLayoutManager) {
                        visibleCount = layoutManager.findLastVisibleItemPosition() - layoutManager.findFirstVisibleItemPosition()
                    }
                }
            })
            homeHotAdapter.setOnItemClickListener { _, _, position ->
                ARouterHelper.navigateToUserInfoActivity(requireActivity(), homeHotAdapter.items[position].uid)
            }
        }
        mBinding.rcvHomeList.setRecycledViewPool(mViewModel.recycledViewPool)
    }

    private fun initRefreshLayout() {
        mBinding.refreshHome.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                viewModel.getOnlineList(pageIndex)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                pageIndex++
                viewModel.getOnlineList(pageIndex)
            }
        })
    }


    override fun onPause() {
        super.onPause()
        showActivity = false
        stopVideo()
    }

    override fun onResume() {
        super.onResume()
        pageIndex = 1
        viewModel.getOnlineList(pageIndex)
        showActivity = true
        mBinding.rcvHomeList.scrollToPosition(0)
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        showActivity = !hidden
    }

    private fun autoPlayVideo(recyclerView: RecyclerView) {
        val layoutManager = recyclerView.layoutManager
        for (i in 0 until visibleCount) {
            if ((layoutManager?.getChildAt(i) != null) && (layoutManager.getChildAt(i)!!.findViewById<MyStyledPlayerView>(R.id.myVideoView) != null)) {
                val styleMediaPlayerView = recyclerView.getChildAt(i).findViewById<MyStyledPlayerView>(R.id.myVideoView)
                val rect = Rect()
                styleMediaPlayerView.getLocalVisibleRect(rect)
                val videoHeight = styleMediaPlayerView.height
                Log.e("tag", (rect.bottom - rect.top).toString())
                val position = layoutManager.getPosition(layoutManager.getChildAt(i)!!)
                Log.e("tag", "layoutManager 在 列表中的位置=$position")
                if (rect.top == 0 && rect.bottom == videoHeight) {
                    val isVideo = homeHotAdapter.getItem(position)!!.mediaList.any { item ->
                        !item.type.isTypeImg()
                    }
                    if (isVideo) {
                        Log.e("tag", "开始播放第" + i + "个item视频" + styleMediaPlayerView.videoUri)
                        val msg = secondHandler?.obtainMessage()
                        msg?.let {
                            msg.what = AUTO_VIDEO
                            msg.obj = styleMediaPlayerView
                            secondHandler?.sendMessageDelayed(msg, autoPlayDelay)
                        }

                        break
                    }
                }
            }
        }
    }


    private fun watchVideo(itemView: MyStyledPlayerView) {
        if (itemView.videoUri.isEmpty()) {
            Log.e("tag", "没找到视频地址")
            return
        }
        if (itemView.isPlay()) {
            Log.e("tag", "已经在播放了")
            return
        }
        playVideo(itemView)
    }


    private fun playVideo(itemView: MyStyledPlayerView) {
        stopVideo()
        Log.e("tag", "替换view")
        palyVideoVidw = itemView
        palyVideoVidw?.let { //            val mediaItem = MediaItem.fromUri(itemView.videoUri)
            //            player?.setMediaItem(mediaItem)
            itemView.videoUri.forEach {
                val mediaItem = MediaItem.fromUri(it)

                player?.addMediaItem(mediaItem)
            }

            itemView.getVideoView().player = player
            player?.volume = 0f
            player?.repeatMode = Player.REPEAT_MODE_ALL
            player?.prepare()
            player?.playWhenReady = true // player?.play()
            //   it.startVideo()


        }
        palyVideoVidw?.startVideo()

    }


    private fun stopVideo() {
        palyVideoVidw?.apply {
            Log.e("tag", "停止播放$oldPosition")
            this.stopVideo() // this.releasePlayer()
            //    player?.playWhenReady = false
            player?.stop()
        } //        player?.release()
        //        player = null

    }





    override fun clickListener() {

    }

    override fun getViewModel(): Class<HomeNewViewMode> = HomeNewViewMode::class.java
}